﻿using UnityEngine;
using System.Collections;
using ProtoBuf.Message;

namespace UI
{
    public enum AttackType
    {
       Attack,
       Defend,
    }

    public class UIFieldRunMapBattleAttack : MonoBehaviour
    {
        public UIFieldRunMap page;
        public GameObject attack,defend;
        public UILabel attackText, defendText;
        public UILabel timer;
        public float costTime;

        public string attackStr,defendStr,timerStr;
        public bool updateTimer = false;
        
        //SCSidePvpFightResult result;
        OkHander ok;

        public void Init( SCSidePvpFightResult result,OkHander ok)
        {
            this.attackStr = TableTextBlo.GetText("field_battle_pvp_attack");
            this.defendStr = TableTextBlo.GetText("field_battle_pvp_defend");
            this.timerStr = TableTextBlo.GetText("field_battle_begin_timer");

            //this.result = result;
            this.ok = ok;

            AttackType at = AttackType.Attack;

            string str = "";
            if (StaticData.playerData.playerId == result.attPlayerId)
            {
                at = AttackType.Attack;
                str = StaticData.playerInfos[result.defPlayerId].info.playerName;
                StaticData.challenger = StaticData.playerData.name;
            }
            else
            {
                at = AttackType.Defend;
                str = StaticData.playerInfos[result.attPlayerId].info.playerName;
                StaticData.challenger = str;
            }

            var delayTime = Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.FieldPVPCountDown;
            Init(at, str,delayTime);
        }

        void Init(AttackType attackType, string otherPlayer,float timer = 3f)
        {
            attack.SetActive(attackType == AttackType.Attack);
            defend.SetActive(attackType == AttackType.Defend);
            costTime = timer;
            
            if(attackType == AttackType.Attack)
            {
                attackText.text = string.Format(attackStr, otherPlayer);
            }
            else
            {
                defendText.text = string.Format(defendStr, otherPlayer);
            }

            this.timer.text = string.Format(timerStr, (int)costTime);

            gameObject.SetActive(true);
            updateTimer = true;
        }

        void Update()
        {
            if (updateTimer)
            {
                costTime -= Time.deltaTime;
                costTime = Mathf.Max(0, costTime);
                timer.text = string.Format(timerStr, (int)costTime);
                if (costTime <= 0)
                {
                    updateTimer = false;
                    BeginAttack();
                    gameObject.SetActive(false);
                }
            }
        }

        /// <summary>
        /// 开始战斗
        /// </summary>
        void BeginAttack()
        {
            ok();
            page.Refresh();
        }
    }
}